/* 参考链接
 https://www.cnblogs.com/elnino/p/11171406.html
*/

package main

import (
    "log"
    "github.com/aws/aws-sdk-go/service/s3"
    "io"
    "os"
)

func (this *S3Mgmt) Download(s3obj, localfile string) error {
    s3Svc, _ := this.NewSessionConnect()
    // Operation calls will be made to the custom endpoint.
    resp, err := s3Svc.GetObject(&s3.GetObjectInput{
        Bucket: &this.bucket_id, //Required 可认为是cpid，也可认为是对于根目录而言的第一级目录.必须先创建，在存储。
        Key:    &s3obj,       //Required 文件名，中间可以带着路径，格式如：{path}/{filename}
        //Range:  aws.String("bytes=0-499"),             //not must be Required 文件范围，如果没有则是全文件
    })
    if err != nil {
        // Print the error, cast err to awserr.Error to get the Code and
        // Message from an error.
        log.Println("hello , i met error")
        log.Println(err.Error())
        return err
    }

    log.Println("AcceptRanges :", *resp.AcceptRanges)
    log.Println("ContentLength:", *resp.ContentLength)
    //fmt.Println("ContentRange :", *resp.ContentRange)
    //fmt.Println("PartsCount   :", *resp.PartsCount)
    // Pretty-print the response data.
    //fmt.Println(resp)

    //数据都在resp.Body中，可以转储到文件，具体操作参考go的操作
    out, err := os.OpenFile(localfile, os.O_CREATE|os.O_RDWR, 0666)
    if out == nil {
        log.Println("Open fail")
        return err
    }
    num, err := io.Copy(out, resp.Body)
    log.Printf("read %d bytes from S3 bucket, err: %v \n", num, err)
    return nil
}
